<template>
  <div id="chatManage">
    <!-- 顶部搜索栏 -->
    <a-form layout="inline" :model="searchParams" class="mb-4 search-form">
      <a-form-item label="消息内容">
        <a-input v-model:value="searchParams.message" placeholder="请输入消息内容" allow-clear />
      </a-form-item>

      <a-form-item label="选择消息类型">
        <a-select
          v-model:value="searchParams.messageType"
          placeholder="选择消息类型"
          style="width: 180px"
          allow-clear
        >
          <a-select-option value="user">用户消息</a-select-option>
          <a-select-option value="ai">AI消息</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="应用ID">
        <a-input v-model:value="searchParams.appId" placeholder="请输入应用ID" allow-clear />
      </a-form-item>

      <a-form-item label="用户ID">
        <a-input v-model:value="searchParams.userId" placeholder="请输入用户ID" allow-clear />
      </a-form-item>

      <a-form-item>
        <a-space>
          <a-button type="primary" @click="handleSearch">搜索</a-button>
          <a-button type="default" @click="handleReset">重置</a-button>
        </a-space>
      </a-form-item>
    </a-form>

    <a-divider style="margin: 16px 0" />

    <!-- 表格 -->
    <a-table
      sticky
      :columns="columns"
      :data-source="data"
      :pagination="pagination"
      @change="handleTableChange"
      :scroll="{ x: 1200 }"
      bordered
      :loading="tableLoading"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'message'">
          <a-tooltip :title="record.message">
            <div class="message-text">{{ record.message }}</div>
          </a-tooltip>
        </template>

        <template v-else-if="column.key === 'messageType'">
          <a-tag :color="record.messageType === 'user' ? 'blue' : 'green'">
            {{ record.messageType === 'user' ? '用户' : 'AI' }}
          </a-tag>
        </template>

        <template v-else-if="column.key === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>

        <template v-else-if="column.key === 'action'"
          ><a-space>
            <a-button type="primary" size="small" @click="goToChat(record.appId)"
              >进入对话</a-button
            >
            <a-popconfirm
              title="确定要删除这条消息吗？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="handleDeleteChat(record.id)"
            >
              <a-button type="primary" size="small" danger><DeleteOutlined /></a-button>
            </a-popconfirm> </a-space
        ></template>
      </template>
    </a-table>
  </div>
</template>

<script lang="ts" setup>
import {
  deleteChatHistoryById,
  listAllChatHistoryByPageForAdmin,
} from '@/api/chatHistoryController'
import { message, type TableColumnsType } from 'ant-design-vue'
import { reactive, ref, onMounted, computed } from 'vue'
import dayjs from 'dayjs'
import { DeleteOutlined } from '@ant-design/icons-vue'
import { useRouter } from 'vue-router'

const columns = ref<TableColumnsType>([
  {
    title: 'ID',
    width: 80,
    dataIndex: 'id',
    key: 'id',
    fixed: 'left',
    align: 'center',
  },
  {
    title: '消息内容',
    width: 300,
    dataIndex: 'message',
    key: 'message',
    align: 'center',
  },
  {
    title: '消息类型',
    dataIndex: 'messageType',
    key: 'messageType',
    width: 100,
    align: 'center',
  },
  {
    title: '应用ID',
    dataIndex: 'appId',
    key: 'appId',
    width: 80,
    align: 'center',
  },
  {
    title: '用户ID',
    dataIndex: 'userId',
    key: 'userId',
    width: 80,
    align: 'center',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 160,
    align: 'center',
  },
  {
    title: '操作',
    key: 'action',
    fixed: 'right',
    width: 180,
    align: 'center',
  },
])

const router = useRouter()

const data = ref<API.ChatHistory[]>([])
const total = ref<number>(0) // 总条数

const tableLoading = ref<boolean>(false)
const deleteLoading = ref<boolean>(false)

const searchParams = reactive<API.ChatHistoryQueryRequest>({
  pageSize: 10,
  pageNum: 1,
})

const pagination = computed(() => ({
  current: searchParams.pageNum ?? 1,
  pageSize: searchParams.pageSize ?? 10,
  total: total.value,
  showSizeChanger: true,
  showTotal: (total: number) => `共 ${total} 条`,
}))

const handleSearch = () => {
  searchParams.pageNum = 1
  getList()
}

const handleReset = () => {
  searchParams.pageNum = 1
  searchParams.pageSize = 10
  searchParams.appId = undefined
  searchParams.userId = undefined
  searchParams.message = undefined
  searchParams.messageType = undefined
  getList()
}

// 表格分页改变
const handleTableChange = (pagination: any) => {
  searchParams.pageNum = pagination.current
  searchParams.pageSize = pagination.pageSize
  getList()
}
const getList = async () => {
  tableLoading.value = true
  try {
    const res = await listAllChatHistoryByPageForAdmin({
      ...searchParams,
    })
    if (res.data.code === 0 && res.data.data) {
      console.log(res, 'res')
      data.value = res.data.data.records || []
      total.value = res.data.data.totalRow || 0
    } else {
      message.error(res.data.message || '获取列表失败')
    }
  } catch (e) {
    message.error('获取列表失败')
  } finally {
    tableLoading.value = false
  }
}

const goToChat = (id: number) => {
  if (!id) return
  router.push({ path: `/app/chat/${id}` })
}

// 删除
const handleDeleteChat = async (id: number) => {
  if (!id) return
  deleteLoading.value = true
  try {
    const res = await deleteChatHistoryById({ id })
    if (res.data.code === 0 && res.data.data) {
      message.success('删除成功')
      if (!data.value.length) {
        searchParams.pageNum && searchParams.pageNum--
      }
      getList()
    } else {
      message.error(res.data.message || '删除失败')
    }
  } catch (error: any) {
    message.error(error.message || '删除失败')
  } finally {
    deleteLoading.value = false
  }
}

onMounted(() => {
  getList()
})
</script>
<style scoped>
#components-table-demo-summary tfoot th,
#components-table-demo-summary tfoot td {
  background: #fafafa;
}
[data-theme='dark'] #components-table-demo-summary tfoot th,
[data-theme='dark'] #components-table-demo-summary tfoot td {
  background: #1d1d1d;
}

#chatManage {
  /* height: 100vh; */
  display: flex;
  flex-direction: column;
  font-family: 'Helvetica Neue', Arial, sans-serif;
  background: #fff;
  padding: 20px 25px;
  margin: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
  overflow: hidden;
  overflow-y: hidden;
}

.message-text {
  /* max-width: 300px; */
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
